package com.xxxx;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;

public class Hello02FlinkKeyedState {

    public static void main(String[] args) throws Exception {
        //获取执行环境
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        //获取数据源
        DataStreamSource<String> source = environment.socketTextStream("192.168.88.101", 18880);
        //开始进行转换,Lambda 一定要主要添加返回类型
        SingleOutputStreamOperator<String> flatMap = source.flatMap((String line, Collector<String> collector) -> {
            Arrays.stream(line.split(" ")).forEach(word -> collector.collect(word));
        }).returns(Types.STRING);
        //开始转换
        flatMap.map(word -> Tuple2.of(word, 1)).returns(Types.TUPLE(Types.STRING, Types.INT))
                .keyBy(0)
                .map(new KeyedStateMapFunction())
                .print();

        //启动流式计算
        environment.execute("Hello02FlinkKeyedState" + System.currentTimeMillis());

    }

}

class KeyedStateMapFunction extends RichMapFunction<Tuple2<String, Integer>, String> {

    private ValueState<Integer> valueState;

    @Override
    public void open(Configuration parameters) throws Exception {
        //获取描述器
        ValueStateDescriptor<Integer> valueStateDescriptor = new ValueStateDescriptor<Integer>("keyedStatWordCount", Integer.class);
        valueState = getRuntimeContext().getState(valueStateDescriptor);
    }

    @Override
    public String map(Tuple2<String, Integer> tuple2) throws Exception {
        int count = 0;
        //首先获取原来的count
        if (valueState != null && valueState.value() != null) {
            count = valueState.value();
        }
        count++;
        valueState.update(count);
        return tuple2.f0 + "--" + count;
    }
}